package org.gl.training.filters;

import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * Servlet Filter implementation class LogFilter
 */
@WebFilter(servletNames = { "LoginServlet", "RegisterServlet" })
public class LogFilter implements Filter {

	Logger logger = Logger.getLogger(LogFilter.class);
	
	/**
	 * Default constructor.
	 */
	public LogFilter() {
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;

		logger.info("---------------------------------------");	
		
		String url = httpServletRequest.getRequestURL().toString();
		logger.info("Accessing this url=" + url);

		Map<String, String[]> parametersMap = request.getParameterMap();
		Set<String> keys = parametersMap.keySet();
		
		logger.debug("Following request paramteres are sent:");	
		for (String key : keys) {
			String[] values = parametersMap.get(key);
			logger.debug("Key=" + key + ", Value=" + Arrays.toString(values));
		}

		logger.info("---------------------------------------");	
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}
}
